package com.heima.filter;

import com.heima.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Slf4j
public class GlobalF implements Ordered, GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求，取出进入网关的request信息
        ServerHttpRequest request = exchange.getRequest();
        //返回响应，返回下一个过滤器，或者直接拦截
        ServerHttpResponse response = exchange.getResponse();

        //判断是否是登录
        if (request.getURI().getPath().contains("/login")) {
            //放行
            return chain.filter(exchange);
        }

        //取出token信息
        String token = request.getHeaders().getFirst("token");

        //判断token是否存在
        if (StringUtils.isEmpty(token)) {
            //返回未认证，并返回给下一个过滤器
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //判断token是否有效
        Claims claimsBody = AppJwtUtil.getClaimsBody(token);
        //判断是否过期，-1：有效，0：有效，1：过期，2：过期
        int verifyToken = AppJwtUtil.verifyToken(claimsBody);
        if (verifyToken == 1 || verifyToken == 2) {
            //token已过期
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        log.info("app端用户通过的token-->{}", token);

        //将app用户信息存到header中，后面要获取信息
        //从claimsBody中取出
        Object userId = claimsBody.get("id");

        //存储到header中
        ServerHttpRequest serverHttpRequest = request.mutate().headers(httpHeaders -> {
            httpHeaders.add("userId", userId.toString());
        }).build();
        //重置请求
        exchange.mutate().request(serverHttpRequest);

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -1;
    }
}
